#include "http.hpp"

#define WWWROOT "./wwwroot/"

std::string OrganizeReqStr(const HttpRequest &req)
{
    std::string str;
    str += req._method + " " + req._path + " " + req._version + "\r\n";
    for (auto &it : req._params)
        str += it.first + ": " + it.second + "\r\n";
    for (auto &it : req._headers)
        str += it.first + ": " + it.second + "\r\n";
    str += "\r\n";
    str += req._body;
    return str;
}

// HTTP服务器各种功能性请求对应的业务处理函数，为了便于测试这里只是简单回显
void Hello(const HttpRequest &req, HttpResponse *rsp)
{
    rsp->SetBody(OrganizeReqStr(req), "text/plain");
    // client4.cc测试业务处理超时
    // sleep(15);
}

void Login(const HttpRequest &req, HttpResponse *rsp)
{
    rsp->SetBody(OrganizeReqStr(req), "text/plain");
}

void UploadFile(const HttpRequest &req, HttpResponse *rsp)
{
    std::string pathname = WWWROOT + req._path;
    Util::WriteFile(pathname, req._body);
}

void DeleteFile(const HttpRequest &req, HttpResponse *rsp)
{
    rsp->SetBody(OrganizeReqStr(req), "text/plain");
}

int main()
{
    HttpServer server(8888);
    server.SetThreadCount(3);
    // 设置静态资源根目录，告诉服务器有静态资源请求到来时，需要到哪里去找资源文件
    server.SetWebroot(WWWROOT);

    // 服务器的使用者自己编写诸多业务处理函数，让服务器针对各种不同的Http请求，进行不同的业务逻辑处理
    server.AddGetRoute("/hello", Hello);
    server.AddPostRoute("/login", Login);
    server.AddPutRoute("/12345.txt", UploadFile);
    server.AddDeleteRoute("/(\\d+).*", DeleteFile);
    server.Run();
    return 0;
}